package com.wan37.logic.handler.message;

import com.wan37.logic.component.Worker;
import com.wan37.logic.domain.vo.MessageVO;
import com.wan37.logic.domain.vo.RoleVO;
import com.wan37.logic.domain.vo.WeaponryVO;
import com.wan37.logic.global.HandlerManager;
import com.wan37.logic.global.reference.SpringContextHolder;
import com.wan37.logic.handler.MsgHandler;
import com.wan37.logic.service.cache.RoleServiceCache;
import com.wan37.logic.service.cache.SceneServiceCache;
import com.wan37.logic.service.cache.UserServiceCache;
import com.wan37.logic.utils.RouteUtils;
import com.wan37.protobuf.constant.BackpackLabel;
import com.wan37.protobuf.constant.Common;
import com.wan37.protobuf.constant.CommonBackpack;
import com.wan37.protobuf.constant.PtoNum;
import com.wan37.protobuf.message.client2server.game.Game;
import com.wan37.protobuf.message.client2server.game.GameBackpack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : luoyong
 * @date : 2020-06-10 17:49
 **/
public class CGameRoleHandler extends MsgHandler {

    private static final Logger logger = LoggerFactory.getLogger("CGameRoleHandler.class");

    private RoleServiceCache roleServiceCache;
    private UserServiceCache userServiceCache;
    private RouteUtils routeUtils;
    private SceneServiceCache sceneServiceCache;

    /**
     * MsgHandler构造函数
     *
     * @param messageVO
     */
    public CGameRoleHandler(MessageVO messageVO) {
        super(messageVO);
        this.roleServiceCache = SpringContextHolder.getBean("roleServiceCache");
        this.userServiceCache = SpringContextHolder.getBean("userServiceCache");
        this.routeUtils = SpringContextHolder.getBean("routeUtils");
        this.sceneServiceCache = SpringContextHolder.getBean("sceneServiceCache");
    }

    @Override
    public void execute(Worker worker) throws Exception {
        Game.CGameRoleMsg cGameRoleMsg = (Game.CGameRoleMsg) messageVO.getMessage();
        String userId = cGameRoleMsg.getUserId();
        String sceneId = sceneServiceCache.sceneNameToIdMap.get(cGameRoleMsg.getScene());
        getRole(userId, sceneId);
    }

    public void getRole(String userId, String sceneId) throws IllegalAccessException, InstantiationException, InvocationTargetException {
        //新场景中的用户集合
        Set<String> userIdSet = sceneServiceCache.getSceneServiceMap().get(sceneId).getUserIdSet();
        //新场景中除我之外的用户集合
        Set<String> userIdSetNotSelf = userIdSet.stream().filter(userId2 -> !userId2.equals(userId)).collect(Collectors.toSet());
        Map<String, List<String>> userIdToRoleVoMap = new HashMap<>();
        userIdSet.forEach(userId1 ->
                userIdToRoleVoMap.put(userId1, userServiceCache.getUserServiceMap().get(userId1).getRoleIdList())
        );
        routeUtils.sendRoleResponse(userIdToRoleVoMap, userId);
        logger.info(userId + ": 获取角色信息已返回！！");

        /**
         * 用户进入场景显示自己之后需要推送自己给当前场景的其他用户显示
         */
        List<String> listRoleId = userServiceCache.getUserServiceMap().get(userId).getRoleIdList();
        List<RoleVO> roleVOList = new ArrayList<>();
        for (String roleId : listRoleId) {
            roleVOList.add(roleServiceCache.getRoleServiceMap().get(roleId).getRoleVO());
        }
        routeUtils.sendAoiRoleBroadcastResponse(Common.GAME_ROLE_SUCCESS,
                sceneServiceCache.getSceneServiceMap().get(sceneId).getUserIdSet()
                        .stream().filter(userId1 -> !userId1.equals(userId)).collect(Collectors.toSet()), roleVOList);
        /**
         * 获取当前场景下所有用户的所有角色的技能
         */
        CGameSkillHandler cGameSkillHandler = (CGameSkillHandler) HandlerManager.getMsgHandler
                (PtoNum.CGAMESKILLMSG, userId, messageVO.getNetId(), null, messageVO.getCtx());
        cGameSkillHandler.getSkill(new ArrayList<>(userIdSet));

        List<String> userIdList = new ArrayList<>();
        userIdList.add(userId);
        routeUtils.sendSkillResponseBroadcast(Common.GAME_GET_SKILL_SUCCESS,
                "", cGameSkillHandler.getAllRoleIdToSkillVOMap(userIdList), userIdSetNotSelf);

        /**
         * 获取请求用户的背包信息（用户不可以获取其他用户的背包信息）
         */
        CGameItemHandler cGameItemHandler = (CGameItemHandler) HandlerManager.getMsgHandler
                (PtoNum.CGAMEITEMMSG, userId, messageVO.getNetId(), null, messageVO.getCtx());
        cGameItemHandler.getItem(userServiceCache.getUserServiceMap().get(userId).getItemVOMap());
        /**
         * 获取自身的武器信息
         */
        CGameWeaponryHandler cGameWeaponryHandler = (CGameWeaponryHandler) HandlerManager.getMsgHandler
                (PtoNum.CGAMEWEAPONRYMSG, userId, messageVO.getNetId(), null, messageVO.getCtx());
        cGameWeaponryHandler.getWeaponry(userServiceCache.getUserServiceMap().get(userId).getWeaponryVOMap());

        /**
         * 获取同场景其他已经装配好的装备信息
         */
        for (String userId1 : userIdSet) {
            List<WeaponryVO> weaponryVOList = new ArrayList<>();
            Map<String, WeaponryVO> weaponryVOMap = userServiceCache.getUserServiceMap().get(userId1).getWeaponryVOMap();
            weaponryVOList.addAll(weaponryVOMap.values().stream().filter(weaponryVO -> !weaponryVO
                    .getUsage().equals(BackpackLabel.WEAPONRY_UNUSED)).collect(Collectors.toList()));
            /**
             * 如果是自己就广播自己出去给同场景中的其他人
             */
            if (userId.equals(userId1)) {
                Map<String, List<WeaponryVO>> userIdToWeaponryMap = new HashMap<>();
                userIdToWeaponryMap.put(userId, weaponryVOList);
                routeUtils.sendWeaponryBroadcastResponse(CommonBackpack.SELF_WEAPONRY_BROADCAST,
                        userIdToWeaponryMap, userIdSetNotSelf, "");
                continue;
            }
            routeUtils.sendWeaponryResponse(CommonBackpack.WEAPONRY_SUCCESS,
                    userId1, userId1 + "装备信息获取成功！", weaponryVOList, messageVO);
        }

    }
}
